package com.cokus.wavelibrary.breathfre;

import android.media.AudioRecord;

import org.apache.commons.math3.analysis.function.Abs;

import java.util.ArrayList;

public class AudioAnalyse {
    private Short[] rawData;
    private static ArrayList<Float> mData=new ArrayList<Float>(); //归一化后的data数组
    private static ArrayList<Float> pData=new ArrayList<Float>();  //平均功率数组
    private static ArrayList<Integer> breathState=new ArrayList<Integer>();  //声音状态数组

    private int breathCount;
    private short min;
    private short max;
    private int step;//判断步长
    private double limit;//阈值
    private int pStep;//平均功率步长

    public int getBreathCount() {
        for (int i = 0; i < rawData.length; i++) {//abs
            rawData[i]=(short)Math.abs(rawData[i]);
        }
        for (int i = 0; i < rawData.length; i++) {
            if (i == 0) {
                min = rawData[i];
                max = rawData[i];
            }
            if (min > rawData[i]) {
                min = rawData[i];
            }
            if (max < rawData[i]) {
                max = rawData[i];
            }
        }
        for (int i = 0; i < rawData.length; i++) {//归一化
            mData.add(((float) rawData[i] - min) / (max - min));
        }
        for (int i = 0; i < (mData.size()-pStep)/step; i++) {
            float tempP=0;
            for (int i1 = 0; i1 < pStep; i1++) {
                tempP=tempP+mData.get(i+i1)*mData.get(i+i1);//P=sigma x(t)^2
            }
            tempP=tempP/pStep;
            pData.add(tempP);
        }
        breathState.add(0);
        for (int i = 0; i < pData.size(); i++) {
            if(pData.get(i)>limit&&breathState.get(breathState.size()-1)==0)breathState.add(1);//大于0.5为发出声音状态
            if(pData.get(i)<limit&&breathState.get(breathState.size()-1)==1)breathState.add(0);
        }
        breathCount=breathState.size()/4;
        return breathCount;
    }

    /**
     *
     * @param rawData 原始数据
     * @param step 检测步长
     * @param pStep  平均功率步长
     * @param limit 阈值
     */
    public AudioAnalyse(Short[] rawData,int step,int pStep,double limit) {
        this.rawData = rawData;
        this.step=step;
        this.pStep=pStep;
        this.limit=limit;
    }
}
